#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: Export user interface
# Created: 02/25/2009
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
# Didrik Pinte --<dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.

import os
import wx

from hydroplatform.model.export import ExporterRegistry, ExportError
from hydroplatform.extension.export import *

class ExportFrame(wx.Frame):
    '''
    This frame shows an export dialog allowing the user to select a registered 
    exporter, a network and an output filename    
    '''
    
    def __init__(self, parent, context):
        '''
        The context is a Thuban context object
        '''
        wx.Frame.__init__(self, parent, -1, u"Export") 
        self.context = context
        self.exportregistry = ExporterRegistry()
        self.elist = [e.getName() for e in self.exportregistry.available_exporters()]
        self.project = context.session.hpproject
        self.ndict = {}
        for network in self.project.networks:
            self.ndict[network.name] = network
        
        self.exporter = None
        self.network = None
        self.filename = None
        self.session = context.session.dbsession
        
        self.doLayout()
        self.bindEvents()
   
    def doLayout(self):
        panel = wx.Panel(self)
       
        # First create the controls
        topLabel = wx.StaticText(panel, -1, u"Export network")
        topLabel.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
        
        # exporter name and combo box for choosing
        nameLabel  = wx.StaticText(panel, -1, u"Exporters :")
        self.exp_ctrl = wx.ComboBox(panel, -1, choices=self.elist,
                                     style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT)
       
        # exporter description
        descLabel = wx.StaticText(panel, -1, u"Description :")
        self.edesc_ctrl = wx.TextCtrl(panel, -1, u"", size=(200,100), 
                                      style=wx.TE_READONLY|wx.TE_MULTILINE)
        
        # network list selection
        networkLabel = wx.StaticText(panel, -1, u"Network :")
        self.netw_ctrl = wx.ComboBox(panel, -1, choices=self.ndict.keys(),
                                     style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT)
        
        # Output file selection
        fileLabel = wx.StaticText(panel, -1, u"Output file :")
        if self.filename is None:
            self.filename = "Select file"    
        self.fileButton = wx.Button(panel, -1, self.filename)
        
        # Buttons
        self.okButton = wx.Button(panel, -1, u"Export")
        self.okButton.Disable()
        self.cancelButton = wx.Button(panel, -1, u"Cancel")
        
        # Now do the layout
        
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(topLabel, 0, wx.ALL, 5)
        mainSizer.Add(wx.StaticLine(panel), 0, 
                      wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
        
        fieldSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        fieldSizer.AddGrowableCol(1)
        fieldSizer.Add(nameLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        fieldSizer.Add(self.exp_ctrl, 0, wx.EXPAND)
        fieldSizer.Add(descLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        fieldSizer.Add(self.edesc_ctrl, 0, wx.EXPAND)
        fieldSizer.Add(networkLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        fieldSizer.Add(self.netw_ctrl, 0, wx.EXPAND)
        fieldSizer.Add(fileLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        fieldSizer.Add(self.fileButton, 0, wx.EXPAND)
        
        mainSizer.Add(fieldSizer, 0, wx.EXPAND | wx.ALL, 10)
        
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add((20,20), 1)
        btnSizer.Add(self.okButton)
        btnSizer.Add((20,20),1)
        btnSizer.Add(self.cancelButton)
        btnSizer.Add((20,20),1)
        
        mainSizer.Add(btnSizer, 0, wx.EXPAND | wx.ALL, 10)
        
        panel.SetSizer(mainSizer)
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self)
    
    def bindEvents(self):
        
        self.Bind(wx.EVT_COMBOBOX, self.OnExporterChange, self.exp_ctrl)
        self.Bind(wx.EVT_COMBOBOX, self.OnNetworkChange, self.netw_ctrl)
        self.Bind(wx.EVT_BUTTON, self.OnFileSelect, self.fileButton)
        self.Bind(wx.EVT_BUTTON, self.OnExport, self.okButton)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancelButton)

    def checkExportButtonStatus(self):
        if self.exporter is not None and self.filename is not None \
           and self.network is not None:
            self.okButton.Enable()
        else : self.okButton.Disable()
        
        
    def OnExporterChange(self, event):
        # get exporter
        exporter_name = event.GetString()
        self.exporter = self.exportregistry.getExporterByName(exporter_name)
        # update description
        self.edesc_ctrl.SetValue(self.exporter.getDescription())
        self.checkExportButtonStatus()
   
    def OnNetworkChange(self, event):
        try:
            self.network = self.ndict[event.GetString()]
            self.checkExportButtonStatus()
        except KeyError, e:
            pass
        
    def OnFileSelect(self, event):
        # show a file selection dialog
        # FIXME : check if defaultDir uses the right expression for windows
        dialog = wx.FileDialog(self, message=u"Choose an output file",
                               defaultDir=os.path.expanduser("~"),
                               style=wx.SAVE | wx.OVERWRITE_PROMPT)
        if dialog.ShowModal() == wx.ID_OK:
            self.filename = dialog.GetPath()
            self.fileButton.SetLabel(self.filename)
        dialog.Destroy() 
        self.checkExportButtonStatus()
        
    def OnExport(self, event):
        try:
            self.exporter.export(self.network, self.filename, self.session)
            wx.MessageBox(u"File exported successfully",
                   caption="Export successfull", style=wx.OK | wx.ICON_INFORMATION) 
            self.Destroy()
        except ExportError, e:
            wx.MessageBox(message=u"Errors during export : \n %s" % e,
                   caption="Problems during export", style=wx.OK | wx.ICON_ERROR) 
 

    def OnCancel(self, event):
        self.Destroy()

        
       
